import net.nutss.*;
import net.nutss.stunt.*;
import java.net.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
/*
by casper not supported
import java.util.*;
*/
import java.util.concurrent.Semaphore;

class EchoClientUDP {

    static Semaphore semaphore = new Semaphore(0);
    static STUNTUDPSocket socket;
    static URI uri;

    static class Handler extends STUNTEventAdapter {

        public void connectUDPHandler(STUNTUDPSocket sock) {
            socket = sock;
            semaphore.release();
        }

        public void errorHandler(Exception e) {
            System.err.println("An error occurred. If this is unexpected, please run with '-d'\n" +
                               "as the first argument and email the log created in EchoClientLog.txt\n" +
                               "to Saikat Guha <saikat@cs.cornell.edu>. Thanks\n");
            e.printStackTrace();
            System.exit(1);
        }

    }

    public static void main(String[] arg) throws Exception {
        try {
            uri = new URI(arg[0].equals("-d") ? arg[1] : arg[0]);
        } catch (Exception e) {
            System.out.printf("Usage:\n\tjava EchoClient [-d] you@your.domain.com\n");
            System.exit(1);
        }
        try {
            //if (arg[0].equals("-d")) Control.logToFile("EchoClientLog.txt");
            STUNTEndpoint sock = new STUNTEndpoint();
            sock.connectUDP(uri, new Handler());
            semaphore.acquire();
            BufferedReader uin = new BufferedReader(new InputStreamReader(System.in));
            ByteBuffer     o = ByteBuffer.allocate(1300);
            String s;
            int k;
            while (true) {
                o.clear();
//                socket.s.receive(o);
                o.flip();
                k = o.remaining();
                System.out.println(new String(o.array(), 0, k));
                if ((s = uin.readLine()) == null) break;
                o.clear();
                o.put(s.getBytes());
                o.flip();
//                socket.s.write(o);
            }
        } catch (Exception e) {
            System.err.println("An error occurred. If this is unexpected, please run with '-d'\n" +
                    "as the first argument and email the log created in EchoServerLog.txt\n" +
                    "to Saikat Guha <saikat@cs.cornell.edu>. Thanks\n");
            e.printStackTrace();
            System.exit(1);
        }
    }

}
